package com.miao.im.support.mq;

import com.miao.im.server.session.SessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/3/11 16:19
 * @Description:
 */
@Component
@Slf4j
public class MqMessageRetryTask {
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Scheduled(initialDelay = 10 * 1000, fixedRate = 60 * 1000)
    public void retrySendMessage() {
        Set<MqMessagePayload> failedMessages = MqMessageFailedStore.getAll();
        if (failedMessages.isEmpty()) {
            return;
        }
        log.info("获取到{}条发送失败消息", failedMessages.size());
        int i = 1;
        for (MqMessagePayload payload : failedMessages) {
            Object message = payload.getMessage();
            String messageId = payload.getId();
            log.info(String.format("------------------重发第%d条消息，id: %s------------------", i, messageId));
            i++;
            rabbitTemplate.convertAndSend(payload.getExchange(), payload.getRoutingKey(), message, payload);
            MqMessageFailedStore.remove(payload);
        }
        log.info("------------------重发完成------------------");
    }
}
